package com.time.workshop.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.time.workshop.API;
import com.time.workshop.App;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.adapter.SelectAdapter;
import com.time.workshop.bean.KeShiName;
import com.time.workshop.bean.RequestOrder;
import com.time.workshop.bean.ResponseShopDetail;
import com.time.workshop.bean.ShopList;
import com.time.workshop.bean.ZhuanJiaName;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.LaoBanDialog;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.OnClickOKListener;

@SuppressLint("SimpleDateFormat")
public class WantGuaHaoActivity extends SuperActivity implements OnClickListener{
	@V
	private ListView xlistView;
	@V
	private ImageView img_login_back;
	@V
	private RelativeLayout info_Layout,time_Layout,name_Layout,
	phone_Layout,keshi_Layout,zhuanjia_Layout;
	@V
	private LinearLayout infoTexts_Layout;
	@V
	private TextView commitOrderTextView,timeTextView,shopNameTextView,shopAddrTextView,advancePriceTextView;
	@V
	private EditText nameEditText,phoneEditText,remarksEditText,peoplecountEditText;
	@V
	private TextView keshiEditText,zhuanjiaEditText;
	@V
	private ScrollView scrollview;
	@V
	private ImageView infoImageView;

	private DatePicker datePicker;  
	private TimePicker timePicker;  
	private AlertDialog dialog;  
	public Calendar time = Calendar.getInstance(Locale.CHINA);  
	private boolean processFlag = true;

	private  LaoBanDialog dlg;
	private ShopList shopList;
	private String keshi_id = "";//科室id
	private String zhuanjia_id = "";//专家id
	//popupWindow
	private LayoutInflater inflater;
	private WindowManager.LayoutParams lp;
	private SelectAdapter<KeShiName> keshiadapter;
	private SelectAdapter<ZhuanJiaName> zhuanjiaadapter;
	private PopupWindow popukeshi;
	private PopupWindow popuzhuanjia;
	private List<KeShiName> datakeshi = new ArrayList<KeShiName>();
	private List<ZhuanJiaName> datazhuanjia = new ArrayList<ZhuanJiaName>();

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_want_guahao);
		inflater = LayoutInflater.from(this);
		lp = getWindow().getAttributes(); // 设置popupWindow弹出后背景的阴影
		init();
	}
	private void init() {
		Injector.getInstance().inject(this);
		img_login_back.setOnClickListener(this);
		commitOrderTextView.setOnClickListener(this);
		time_Layout.setOnClickListener(this);
		keshi_Layout.setOnClickListener(this);
		zhuanjia_Layout.setOnClickListener(this);
		info_Layout.getBackground().setAlpha(229);//90%透明度
		time_Layout.getBackground().setAlpha(204);//80%透明度
		name_Layout.getBackground().setAlpha(178);//70%透明度
		phone_Layout.getBackground().setAlpha(153);//60%透明度
		keshi_Layout.getBackground().setAlpha(127);//50%透明度
		zhuanjia_Layout.getBackground().setAlpha(102);//40%透明度
		commitOrderTextView.getBackground().setAlpha(153);//60%透明度
		infoTexts_Layout.getBackground().setAlpha(235);//10%透明度

		scrollview.setBackgroundResource(R.drawable.bg);

		setView();

	}

	private void setView(){
		shopList = (ShopList) getIntent().getSerializableExtra("shoplist");
		requestDetail(shopList.getID());
	}

	private void requestDetail(String id) {
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.GET, API.shopDetail + "?id=" + id,
				new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				try {
					if (responseInfo.result != null) {
						Gson gson = new Gson();
						ResponseShopDetail detail = gson.fromJson(
								responseInfo.result,
								ResponseShopDetail.class);
						shopNameTextView.setText(detail.NAME);
						shopAddrTextView.setText(detail.ADDRESS);
						advancePriceTextView.setText(detail.PRICE+"元起");
						ImageLoader.getInstance().displayImage(
								detail.PIC_URL, infoImageView,
								getDisplayOption());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println(msg);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_login_back:
			CommonUtils.hide(this);
			back();
			break;
		case R.id.commitOrderTextView:
			if (check()) {
				showConfirmDialog();
			}
			break;
		case R.id.time_Layout:
			if (processFlag == true) {
				dateTimePickerDialog();  
				processFlag = false;
				new TimeThread().start(); 
			}
			break;
		case R.id.keshi_Layout:
			getKeShiName();
			break;
		case R.id.zhuanjia_Layout:
			if (!CommonUtils.isNull_nie(keshi_id)) {
				getZhuanJiaName();
			}else {
				NewToast.makeText(getApplicationContext(),"请先选择科室");
			}
			break;
		default:
			break;
		}
	}	
	/*
	 * 选择科室
	 */
	private void getKeShiName() {
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("store_id", shopList.getID());

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.departmentList,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo.result+"");

				if (responseInfo.result.length() != 0) {


					try {
						JSONArray jsonObject = new JSONArray(responseInfo.result);

						Gson gson = new Gson();

						datakeshi = gson.fromJson(jsonObject.toString(), new TypeToken<List<KeShiName>>() {
						}.getType());

						if (datakeshi.size() != 0) {
							chooseKeShiPopu();
						}else {
							NewToast.makeText(getApplicationContext(),"暂时没有可共选择的科室");
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.get_country_failure);
			}
		});
	}
	/*
	 * 专家姓名
	 */
	private void getZhuanJiaName() {
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("department_id", keshi_id);

		HttpUtils httpUtils = new HttpUtils();

		httpUtils.send(HttpMethod.GET, API.personList,params,new RequestCallBack<String>() {

			@Override 
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo.result+"");

				if (responseInfo.result.length() != 0) {


					try {
						JSONArray jsonObject = new JSONArray(responseInfo.result);

						Gson gson = new Gson();

						datazhuanjia = gson.fromJson(jsonObject.toString(), new TypeToken<List<ZhuanJiaName>>() {
						}.getType());

						if (datazhuanjia.size() != 0) {
							chooseZhuanJiaPopu();
						}else {
							NewToast.makeText(getApplicationContext(),"暂时没有数据");
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), R.string.get_country_failure);
			}
		});
	}
	/**
	 * 显示  Dailog 
	 */
	private void showConfirmDialog() {

		dlg = new LaoBanDialog(WantGuaHaoActivity.this);
		if (dlg.isShowing()) {
			dlg.dismiss();
			return;
		}
		dlg.onCreate();
		dlg.setOnClickOK(new OnClickOKListener() {

			@Override
			public void setOnClickOK() {
				submitOrder();

			}
		});

	}
	private void dismisMyDialog() {

		if(  dlg != null && dlg.isShowing() ){
			dlg.dismiss();
		}
		dlg = null;

	}

	private void submitOrder() {

		//		ORDER_TYPE:订单类型(GHDD:挂号;LCWDD:遛宠物;LRDS:老人专区打扫;LRMC:老人专区买菜;
		//		              LRPL:老人专区陪聊;PPDD:陪跑:TCDD:同城;WMDD:外卖;YDDD:订座)
		//		token:登录token
		//		remark:备注
		//		contactor_person：联系人姓名
		//		contactor_phone：联系电话
		//		reservation_time:订座时间
		//		reservation_person:订座人数
		//		contactor_address:联系地址
		//		store_id：店铺ID
		//		Intent in = new Intent(WantGuaHaoActivity.this , ConfirmOrderActivity.class);
		//		in.putExtra("remark", remarksEditText.getText().toString().trim());
		//		in.putExtra("name", nameEditText.getText().toString().trim());
		//		in.putExtra("phone", phoneEditText.getText().toString().trim());
		//		in.putExtra("dingzuotime", remarksEditText.getText().toString().trim());
		//		in.putExtra("dingzuomun", peoplecountEditText.getText().toString().trim());
		//		in.putExtra("store_id", shopList.getID());
		//		in.putExtra("price", shopList.getPRICE());
		//		startActivity(in, true);
		//		finish();
		dlg.dismiss();
		RequestOrder requestOrder = new RequestOrder();
		requestOrder.ORDER_TYPE = "GHDD";
		requestOrder.contactor_person = nameEditText.getText().toString().trim();
		requestOrder.contactor_phone = phoneEditText.getText().toString().trim();
		requestOrder.reservation_time = timeTextView.getText().toString().trim();
		requestOrder.DEPARTMENT_ID = keshi_id;
		requestOrder.PERSON_ID = zhuanjia_id;
		requestOrder.store_id = shopList.getID();
		//requestOrder.remark = remarksEditText.getText().toString().trim();
		//requestOrder.reservation_person = peoplecountEditText.getText().toString().trim();
		//requestOrder.store_id = shopList.getID();
		//requestOrder.price = shopList.getPRICE();
		API.submitOrder(requestOrder, WantGuaHaoActivity.this);
	}
	//选择时间
	public AlertDialog dateTimePickerDialog(){  
		LinearLayout dateTimeLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.date_time_picker, null);  
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.DatePicker);  
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.TimePicker);  
		timePicker.setIs24HourView(true);  

		OnTimeChangedListener timeListener= new OnTimeChangedListener() {  
			@Override  
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {  
				time.set(Calendar.HOUR_OF_DAY, hourOfDay);  
				time.set(Calendar.MINUTE, minute);  

			}  
		};  

		timePicker.setOnTimeChangedListener(timeListener);  
		OnDateChangedListener dateListener = new OnDateChangedListener() {  

			@Override  
			public void onDateChanged(DatePicker view, int year, int monthOfYear,  
					int dayOfMonth) {  
				time.set(Calendar.YEAR, year);  
				time.set(Calendar.MONTH, monthOfYear);  
				time.set(Calendar.DAY_OF_MONTH, dayOfMonth);  
			}  
		};  

		datePicker.init(time.get(Calendar.YEAR), time.get(Calendar.MONTH), time.get(Calendar.DAY_OF_MONTH), dateListener);  
		timePicker.setCurrentHour(time.get(Calendar.HOUR_OF_DAY));  
		timePicker.setCurrentMinute(time.get(Calendar.MINUTE));  

		dialog = new AlertDialog.Builder(this).setTitle("设置日期时间").setView(dateTimeLayout)  
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
					@Override  
					public void onClick(DialogInterface dialog, int which) {  

						time.set(Calendar.YEAR, datePicker.getYear());  
						time.set(Calendar.MONTH, datePicker.getMonth());  
						time.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());  
						time.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());  
						time.set(Calendar.MINUTE, timePicker.getCurrentMinute());  
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
						timeTextView.setText(format.format(time.getTime()));
					}  
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {  
					@Override  
					public void onClick(DialogInterface dialog, int which) {  

					}  
				}).show();  
		return dialog;  
	} 

	private class TimeThread extends Thread {    
		public void run() {  
			try {  
				Thread.sleep(2000);  
				processFlag = true;  
			} catch (Exception e) {  
				e.printStackTrace();  
			}  
		}  
	} 
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dismisMyDialog();
	}
	private boolean check() {
		if (CommonUtils.isNull_nie(nameEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"姓名不能为空");
			return false;
		}else if (CommonUtils.isNull_nie(phoneEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"电话不能为空");
			return false;
		}else if (!CommonUtils.isMobile(phoneEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"电话号码格式错误");
			return false;
		}else if (CommonUtils.isNull_nie(keshi_id)) {
			NewToast.makeText(getApplicationContext(),"请选择科室");
			return false;
		}else if (CommonUtils.isNull_nie(phoneEditText.getText().toString().trim())) {
			NewToast.makeText(getApplicationContext(),"请选择专家");
			return false;
		}else {
			return true;
		}
	}

	/*
	 * 选择科室
	 */
	private void chooseKeShiPopu() {

		View selectView = inflater.inflate(R.layout.pop_selector_keshi, null);
		ListView listViewkeshi = (ListView) selectView.findViewById(R.id.list_one);
		int height = datakeshi.size();
		if (datakeshi.size() > 5) {
			height = 5;
			LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) listViewkeshi.getLayoutParams();
			params.height = keshi_Layout.getHeight()*height;
			listViewkeshi.setLayoutParams(params);
		}
		keshiadapter = new SelectAdapter<KeShiName>(this, datakeshi);
		listViewkeshi.setAdapter(keshiadapter);
		listViewkeshi.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String name = datakeshi.get(position).getNAME();
				keshiEditText.setText(name);
				zhuanjiaEditText.setText("");//选择科室时，专家清空
				keshi_id = datakeshi.get(position).getID();
				keshiadapter.notifyDataSetChanged();
				popukeshi.dismiss();
			}
		});

		popukeshi = new PopupWindow(selectView);
		popukeshi.setWidth(keshi_Layout.getWidth());
		popukeshi.setHeight(LayoutParams.WRAP_CONTENT);
		popukeshi.setOutsideTouchable(true);
		popukeshi.setFocusable(true);
		lp.alpha = 0.4f;
		getWindow().setAttributes(lp);
		popukeshi.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				lp.alpha = 1.0f;
				getWindow().setAttributes(lp);
			}
		});
		popukeshi.setBackgroundDrawable(new ColorDrawable());

		int[] location = new int[2];  
		keshi_Layout.getLocationOnScreen(location);
		popukeshi.setAnimationStyle(R.style.TypeSelAnimationFadeBottom);
		popukeshi.showAtLocation(keshi_Layout, Gravity.NO_GRAVITY,
				location[0], location[1]-keshi_Layout.getHeight()*height);
	}
	/*
	 * 选择专家
	 */
	private void chooseZhuanJiaPopu() {

		View selectView = inflater.inflate(R.layout.pop_selector_keshi, null);
		ListView listViewZhuanJia = (ListView) selectView.findViewById(R.id.list_one);
		int height = datazhuanjia.size();
		if (datazhuanjia.size() > 5) {
			height = 5;
			LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) listViewZhuanJia.getLayoutParams();
			params.height = zhuanjia_Layout.getHeight()*height;
			listViewZhuanJia.setLayoutParams(params);
		}
		zhuanjiaadapter = new SelectAdapter<ZhuanJiaName>(this, datazhuanjia);
		listViewZhuanJia.setAdapter(zhuanjiaadapter);
		listViewZhuanJia.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				zhuanjiaEditText.setText(datazhuanjia.get(position).getNAME());
				zhuanjia_id = datazhuanjia.get(position).getID();
				zhuanjiaadapter.notifyDataSetChanged();
				popuzhuanjia.dismiss();
			}
		});

		popuzhuanjia = new PopupWindow(selectView);
		popuzhuanjia.setWidth(zhuanjia_Layout.getWidth());
		popuzhuanjia.setHeight(LayoutParams.WRAP_CONTENT);
		popuzhuanjia.setOutsideTouchable(true);
		popuzhuanjia.setFocusable(true);
		lp.alpha = 0.4f;
		getWindow().setAttributes(lp);
		popuzhuanjia.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				lp.alpha = 1.0f;
				getWindow().setAttributes(lp);
			}
		});
		popuzhuanjia.setBackgroundDrawable(new ColorDrawable());
		int[] location = new int[2];  
		zhuanjia_Layout.getLocationOnScreen(location);
		popuzhuanjia.setAnimationStyle(R.style.TypeSelAnimationFadeBottom);
		popuzhuanjia.showAtLocation(zhuanjia_Layout, Gravity.NO_GRAVITY, 
				location[0], location[1]-zhuanjia_Layout.getHeight()*height);
	}
}
